package com.hiray.demos.widget


import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Handler
import android.util.AttributeSet
import android.util.Log
import android.widget.TextView

import java.util.ArrayList

@SuppressLint("AppCompatCustomView")
class RandomTextView : TextView {
    //偏移速度类型
    private val pianyiliangTpye: Int = 0

    //   滚动总行数 可设置
    private var maxLine = 10
    //   当前字符串长度
    private var numLength = 0
    //   当前text
    private var text: String? = null


    //滚动速度数组
    private var pianyilianglist: IntArray? = null
    //总滚动距离数组
    private var pianyiliangSum: IntArray? = null
    //滚动完成判断
    private var overLine: IntArray? = null

    private var p: Paint? = null
    //第一次绘制
    private var firstIn = true
    //滚动中
    private var auto = true

    //text int值列表
    private var arrayListText: ArrayList<Int>? = null

    //字体宽度
    private var f0: Float = 0.toFloat()

    //基准线
    private var baseLine: Int = 0

    private var measureHeight: Int = 0

    private val task = object : Runnable {

        override fun run() {
            // TODO Auto-generated method stub
            if (auto) {
                Log.d("RandomTextView", "" + auto)
                handler.postDelayed(this, 100)

                for (j in 0 until numLength) {
                    pianyiliangSum!![j] -= pianyilianglist!![j]

                }

                invalidate()
            }

        }
    }


    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    //按系统提供的类型滚动
    fun setPianyilian(pianyiliangTpye: Int) {
        this.text = getText().toString()

        pianyiliangSum = IntArray(text!!.length)
        overLine = IntArray(text!!.length)
        pianyilianglist = IntArray(text!!.length)
        when (pianyiliangTpye) {
            FIRSTF_FIRST -> for (i in 0 until text!!.length) {
                pianyilianglist!![i] = 20 - i
            }
            FIRSTF_LAST -> for (i in 0 until text!!.length) {
                pianyilianglist!![i] = 15 + i
            }
            ALL -> for (i in 0 until text!!.length) {
                pianyilianglist!![i] = 15
            }
        }
    }

    //自定义滚动速度数组
    fun setPianyilian(list: IntArray) {
        this.text = getText().toString()

        pianyiliangSum = IntArray(list.size)
        overLine = IntArray(list.size)
        pianyilianglist = list


    }


    override fun onDraw(canvas: Canvas) {

        Log.d("RandomTextView", "draw")
        if (firstIn) {
            firstIn = false
            super.onDraw(canvas)
            p = paint
            val fontMetrics = p!!.fontMetricsInt
            measureHeight = getMeasuredHeight()
            Log.d("EEEEEEE", "onDraw: $measureHeight")
            baseLine = (measureHeight - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top
            val widths = FloatArray(4)
            p!!.getTextWidths("9999", widths)
            f0 = widths[0]
            invalidate()
        }
        drawNumber(canvas)
        //        if (auto) {
        //            for (int j = 0; j < numLength; j++) {
        //
        //                pianyiliangSum[j] -= pianyilianglist[j];
        //                postInvalidateDelayed(17);
        //            }


        //     }
    }


    //绘制
    private fun drawNumber(canvas: Canvas) {

        for (j in 0 until numLength) {

            for (i in 1 until maxLine) {


                if (i == maxLine - 1 && i * baseLine + pianyiliangSum!![j] <= baseLine) {
                    pianyilianglist!![j] = 0
                    overLine!![j] = 1
                    var auto = 0
                    for (k in 0 until numLength) {
                        auto += overLine!![k]
                    }
                    if (auto == numLength * 2 - 1) {

                        handler.removeCallbacks(task)
                        //修复停止后绘制问题
                        if (this.auto)
                            invalidate()
                        this.auto = false
                    }

                }
                if (overLine!![j] == 0)

                    drawText(canvas, setBack(arrayListText!![j], maxLine - i - 1).toString() + "", 0 + f0 * j,
                            (i * baseLine + pianyiliangSum!![j]).toFloat(), p)
                else {
                    //定位后画一次就好啦
                    if (overLine!![j] == 1) {
                        overLine!![j]++

                        drawText(canvas, arrayListText!![j].toString() + "", 0 + f0 * j,
                                baseLine.toFloat(), p)
                        // canvas.drawText(arrayListText.get(j) + "", 0 + f0 * j,
                        //        baseLine, p);
                    }

                    //break;
                }//canvas.drawText(setBack(arrayListText.get(j), maxLine - i - 1) + "", 0 + f0 * j,
                //        i * baseLine + pianyiliangSum[j], p);


            }


        }
    }
    var d = false
    val TAG = "RandomTextView"
    //设置上方数字0-9递减 1 8
    private fun setBack(c: Int, back: Int): Int {

        var back = back

        if (back == 0) return c

        back = back % 10

        var re = c - back

        if (re < 0) re = re + 10
        if (!d)
            Log.i(TAG, "setBack:$c  $back  $re")
        d= true
        return re
    }

    //开始滚动
    fun start() {

        this.text = getText().toString()
        numLength = text!!.length

        arrayListText = getList(text!!)

        handler.postDelayed(task, 17)

        auto = true

    }

    private fun getList(s: String): ArrayList<Int> {

        val arrayList = ArrayList<Int>()

        for (i in 0 until s.length) {

            val ss = s.substring(i, i + 1)

            val a = Integer.parseInt(ss)

            arrayList.add(a)
        }
        return arrayList

    }

    fun destroy() {
        auto = false
        handler.removeCallbacks(task)

    }


    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        destroy()
    }

    private fun drawText(mCanvas: Canvas, text: String, x: Float, y: Float, p: Paint?) {

        if (y >= -measureHeight && y <= 2 * measureHeight)

            mCanvas.drawText(text + "", x,
                    y, p!!)
        else
            return
    }

    companion object {
        //高位快
        val FIRSTF_FIRST = 0
        //高位慢
        val FIRSTF_LAST = 1
        //速度相同
        val ALL = 2
        //用户自定义速度
        val USER = 3


        private val handler = Handler()
    }


}